package com.example.UI;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.UI.database.MySQLDataHelper;
import com.example.UI.entity.User;
import com.example.ui.R;


public class RegisterActivity extends AppCompatActivity {
    private MySQLDataHelper mySQLDataHelper1;
    private EditText mUsername;
    private EditText mPassword;
    private EditText mName;
    private EditText mId;
    private Spinner mClass;
    private Button mRegister;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mySQLDataHelper1 = new MySQLDataHelper(this);
        mUsername = findViewById(R.id.r_et_username);
        mPassword = findViewById(R.id.r_et_psw);
        mName = findViewById(R.id.r_et_name);
        mId = findViewById(R.id.r_et_id);
        mClass = findViewById(R.id.spinner_class);
        mRegister = findViewById(R.id.r_bt_register);
        mRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Register(v);
            }
        });
    }

    // 在 RegisterActivity 类的 Register 方法中
    public void Register(View view){
        String s = mUsername.getText().toString().trim();
        String p = mPassword.getText().toString().trim();
        String n = mName.getText().toString().trim();
        String i = mId.getText().toString().trim();
        String c = mClass.getSelectedItem().toString(); // 确保选择不为空

        if (s.isEmpty() || p.isEmpty() || n.isEmpty() || i.isEmpty() || c.isEmpty()) {
            Toast.makeText(this, "填写的信息不完整，请检查！", Toast.LENGTH_SHORT).show();
            return;
        }

        User u = new User(s, p, n, i, c); // 注意构造函数参数的顺序
        long l = mySQLDataHelper1.register(u);
        if (l != -1){
            Toast.makeText(this,"注册成功!",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
            finish(); // 关闭注册Activity
        }else {
            Toast.makeText(this,"注册失败，该学号已注册！",Toast.LENGTH_SHORT).show();
        }
    }
}
